package cn.kt.springbootuploadmaster.service.impl;

import cn.kt.springbootuploadmaster.domin.FileChunkParam;
import cn.kt.springbootuploadmaster.domin.LocalStorage;
import cn.kt.springbootuploadmaster.repository.LocalStorageRepository;
import cn.kt.springbootuploadmaster.service.LocalStorageService;
import cn.kt.springbootuploadmaster.utils.FileUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.UnsupportedEncodingException;

/**
 * Created by tao.
 * Date: 2022/7/1 10:41
 * 描述:
 */
@Service
@Slf4j
public class LocalStorageServiceImpl implements LocalStorageService {
    @Autowired
    private LocalStorageRepository localStorageRepository;

    @Value("${file.BASE_FILE_SAVE_PATH}")
    private String BASE_FILE_SAVE_PATH;

    @Override
    public LocalStorage findByMd5(String md5) {
        return localStorageRepository.findByIdentifier(md5);
    }

    @Override
    public void saveLocalStorage(LocalStorage localStorage) {
        localStorageRepository.save(localStorage);
    }

    @Override
    public void saveLocalStorage(FileChunkParam param) {
        Long id = null;
        LocalStorage byIdentifier = localStorageRepository.findByIdentifier(param.getIdentifier());
        if (!ObjectUtils.isEmpty(byIdentifier)) {
            id = byIdentifier.getId();
        }
        String name = param.getFilename();
        String suffix = FileUtil.getExtensionName(name);
        String type = FileUtil.getFileType(suffix);
        LocalStorage localStorage = new LocalStorage(
                id,
                name,
                FileUtil.getFileNameNoEx(name),
                suffix,
                param.getRelativePath(),
                type,
                FileUtil.getSize(param.getTotalSize().longValue()),
                param.getIdentifier()
        );
        localStorageRepository.save(localStorage);
    }

    @Override
    public void delete(LocalStorage localStorage) {
        localStorageRepository.delete(localStorage);
    }

    @Override
    public void deleteById(Long id) {
        localStorageRepository.deleteById(id);
    }

    @Override
    public void downloadByName(String name, String md5, HttpServletRequest request, HttpServletResponse response) {
        LocalStorage storage = localStorageRepository.findByRealNameAndIdentifier(name, md5);
        if (ObjectUtils.isEmpty(storage)) {
            return;
        }
        File tofile = new File(BASE_FILE_SAVE_PATH + File.separator + storage.getPath());
        try {
            FileUtil.downloadFile(request, response, tofile, false);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }
}
